package com.zxbg.service.impl.systemtoolsServiceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zxbg.dao.*;
import com.zxbg.domain.*;
import com.zxbg.domain.Process;
import com.zxbg.service.systemtoolsService.OrganizationalStructureService;
import com.zxbg.service.systemtoolsService.ProcessManagePlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ProcessManagePlatformServiceImpl implements ProcessManagePlatformService {
    @Autowired
    ProcessRuleDao processRuleDao;
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    OrganizationalStructureServiceImpl organizationalStructureService;
    @Autowired
    ProcessRuleContentDao processRuleContentDao;
    @Autowired
    DepartmentDao departmentDao;
    @Autowired
    ProcessDao processDao;
    @Autowired
    AppDao appDao;

    @Override
    public String addRule(ProcessRule processRule) {
        ProcessRule processRule1 = processRuleDao.getProcessRuleByCode(processRule.getProcess_rule_code(), processRule.getTenant_id());
        if(processRule1 != null) {
            return "code不可重复";
        }
        processRuleDao.addRule(processRule);
        return "";
    }

    @Override
    public List<ProcessRule> getAllProcessRule(String key, Integer tenant_id, boolean ifSysadmin, String employee_id) {
        List<ProcessRule> processRuleList = new ArrayList<>();
        if(ifSysadmin) {
            processRuleList = processRuleDao.getAllProcessRule("%" + key.replace("\"", "") + "%", tenant_id);
        } else {
            processRuleList = processRuleDao.getAllProcessRuleByCreator("%" + key.replace("\"", "") + "%", tenant_id, employee_id);
        }
        if(processRuleList.size() > 0) {
            for (ProcessRule processRule : processRuleList) {
                processRule.setCreator(organizationalStructureService.getAllKindsDept(employeeDao.getEmployeeByEmployeeId(processRule.getCreator_id(), tenant_id)));
                processRule.setUpdater(organizationalStructureService.getAllKindsDept(employeeDao.getEmployeeByEmployeeId(processRule.getUpdater_id(), tenant_id)));
            }
        }
        return processRuleList;
    }

    @Override
    public boolean updateProcessRule(ProcessRule processRule) {
        return processRuleDao.updateProcessRule(processRule) > 0;
    }

    @Override
    public boolean deleteProcessRule(String process_rule_code, Integer tenant_id) {
        List<ProcessRuleContent> processRuleContentList = processRuleContentDao.getProcessRuleContent(process_rule_code, tenant_id);
        for (ProcessRuleContent processRuleContent : processRuleContentList) {
            processRuleContentDao.deleteContentById(processRuleContent.getId());
        }
        processRuleDao.deleteProcessRule(process_rule_code, tenant_id);
        // 待补充：对流程表的更改
        return true;
    }

    @Override
    public List<ProcessRuleContent> getProcessRuleContent(String process_rule_code, Integer tenant_id) {
        List<ProcessRuleContent> processRuleContentList = processRuleContentDao.getProcessRuleContent(process_rule_code, tenant_id);
        for (ProcessRuleContent processRuleContent : processRuleContentList) {
            processRuleContent.setButtons_set(processRuleContent.getButton_id().split(","));
            String select_mode = processRuleContent.getSelect_mode();
            if(select_mode != null && select_mode != "") {
                if(select_mode.equals("targetPerson")) {
                    processRuleContent.setTarget_person(organizationalStructureService.getAllKindsDept(employeeDao.getEmployeeByEmployeeId(processRuleContent.getSetting(), tenant_id)));
                } else if(select_mode.equals("lineUp")) {
                    int[] integers = Arrays.stream(processRuleContent.getSetting().split(",")).mapToInt(Integer::parseInt).toArray();
                    List<Integer> integerList = new ArrayList<>();
                    for (int num : integers) {
                        integerList.add(Integer.valueOf(num));
                    }
                    processRuleContent.setLine_up(integerList);
                } else {
                    processRuleContent.setTarget_dept(departmentDao.getDeptById(Integer.parseInt(processRuleContent.getSetting())));
                }
            }
        }
        return processRuleContentList;
    }

    @Override
    public boolean saveProcessRuleContent(List<ProcessRuleContent> processRuleContentList, Integer tenant_id, Integer status) {
        String process_rule_code = processRuleContentList.get(0).getProcess_rule_code();
        for (int i = 0; i < processRuleContentList.size(); i++) {
            ProcessRuleContent processRuleContent = processRuleContentList.get(i);
            processRuleContent.setTenant_id(tenant_id);
            processRuleContent.setButton_id(String.join(",", processRuleContent.getButtons_set()));
            processRuleContent.setOrder(i+1);
            processRuleContentDao.saveProcessRuleContent(processRuleContent);
        }
        if(status == 1) {
            processRuleDao.setStatusBy(process_rule_code, tenant_id);
        }
        return true;
    }

    @Override
    public boolean updateProcessRuleContent(List<ProcessRuleContent> processRuleContentList, Integer tenant_id, Integer status, String employee_id) {
        String process_rule_code = processRuleContentList.get(0).getProcess_rule_code();
        List<Integer> integerList = processRuleContentDao.getProcessRuleContentId(process_rule_code, tenant_id);
        List<Integer> newIdList = new ArrayList<>();
        for (int i = 0; i < processRuleContentList.size(); i++) {
            ProcessRuleContent processRuleContent = processRuleContentList.get(i);
            processRuleContent.setButton_id(String.join(",", processRuleContent.getButtons_set()));
            processRuleContent.setOrder(i+1);
            if(processRuleContent.getId() != null && !processRuleContent.getId().equals("")) {
                newIdList.add(processRuleContent.getId());
                processRuleContentDao.updateProcessRuleContent(processRuleContent);
            } else {
                processRuleContent.setTenant_id(tenant_id);
                processRuleContentDao.saveProcessRuleContent(processRuleContent);
            }
        }
        for (Integer oldId : integerList) {
            if(!newIdList.contains(oldId)) {
                processRuleContentDao.deleteContentById(oldId);
            }
        }
        if(status == 1) {
            processRuleDao.setStatusBy(process_rule_code, tenant_id);
        }
        processRuleDao.updateUpdater(process_rule_code, employee_id, tenant_id);
        return true;
    }

    @Override
    public List<Process> getProcessList(Map<String, Object> search_info, Integer tenant_id, String employee_id) {
        Employee employee = employeeDao.getEmployeeByEmployeeId(employee_id, tenant_id);
        List<Process> res = new ArrayList<>();
        if(employee.getIs_sysadmin() == 1) {
            // 接收处理查询参数
            Employee current_task_employee = new Employee();
            String process_id = (String) search_info.get("processId");
            String process_name = (String) search_info.get("processName");
            String process_status = (String) search_info.get("processStatus");
            Employee submit_employee = new Employee();
            List<Date> submit_time = new ArrayList<>();
            String jsonObject = JSON.toJSONString(search_info.get("nowDoPerson"));
            if (!jsonObject.equals("")) {
                current_task_employee = JSONObject.parseObject(jsonObject, Employee.class);
            }
            jsonObject = JSON.toJSONString(search_info.get("submitPerson"));
            if (!jsonObject.equals("")) {
                submit_employee = JSONObject.parseObject(jsonObject, Employee.class);
            }
            jsonObject = JSON.toJSONString(search_info.get("submitTime"));
            if (!jsonObject.equals("")) {
                submit_time = JSONObject.parseObject(jsonObject, List.class);
            }
            // 获取所有流程以及完整信息
            List<Process> allProcess = processDao.getAllProcess(tenant_id);
            if(allProcess != null) {
                for (Process process : allProcess) {
                    String current_process_name = processRuleDao.getProcessRuleByCode(process.getProcess_rule_code(), tenant_id).getProcess_rule_name();
                    Date current_submit_time = process.getSubmit_time();
                    String currentHandler = process.getCurrent_task_handler();
                    List<String> curHandlerList = new ArrayList<>();
                    if(currentHandler != null && !currentHandler.equals("")) {
                        curHandlerList = Arrays.asList(currentHandler.split(","));
                    }
                    if(
                        (
                            current_task_employee.getEmployee_id() == null ||
                            curHandlerList.contains(current_task_employee.getEmployee_id())
                        ) &&
                        (
                            (process_id == null || process_id.equals("")) ||
                            process.getProcess_id() == Integer.parseInt(process_id)
                        ) &&
                        (
                            (process_name == null || process_name.equals("")) ||
                            current_process_name.equals(process_name)
                        ) &&
                        (
                            (process_status == null || process_status.equals("")) ||
                            process.getProcess_status().equals(process_status)
                        ) &&
                        (
                            submit_employee.getEmployee_id() == null ||
                            process.getSubmit_employee_id().equals(submit_employee.getEmployee_id())
                        ) &&
                        (
                            submit_time.size() == 0 ||
                            (submit_time.get(0).before(current_submit_time) && submit_time.get(1).after(current_submit_time))
                        )
                    ) {
                        List<Employee> employeeList = new ArrayList<>();
                        for (String id : curHandlerList) {
                            Employee temp = employeeDao.getEmployeeByEmployeeId(id, tenant_id);
                            employeeList.add(organizationalStructureService.getAllKindsDept(temp));
                        }
                        process.setSubmit_employee(employeeDao.getEmployeeByEmployeeId(process.getSubmit_employee_id(), tenant_id));
                        process.setProcess_rule(processRuleDao.getProcessRuleByCode(process.getProcess_rule_code(), tenant_id));
                        process.setCurrent_task_employee(employeeList);
                        res.add(process);
                    }
                }
            }
        }
        return res;
    }
}
